<template>
  <div>

    <!-- 条件列表 -->
    <div style="text-align:left" v-if="flg.searchFlg">
      <el-form :inline="true" :model="queryCondition" class="demo-form-inline">
        <el-form-item label="角色名称" style="font-weight: bold">
          <el-input v-model="queryCondition.name" placeholder="角色名称" size="mini"></el-input>
        </el-form-item>
        <el-form-item label="状态" style="font-weight: bold">
          <el-select v-model="queryCondition.isDelete" prop="isDelete" size="mini">
            <el-option label="正常" value="0"></el-option>
            <el-option label="停用" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getRoleList" size="mini">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 条件列表 -->

    <!-- 操作列表 -->
    <el-row style="margin-bottom:10px">
      <el-col :span="12" style="text-align:left">

        <el-button type="primary" icon="el-icon-plus" size="mini" plain @click="clickDialog('insert')">新增</el-button>
        <el-button type="success" icon="el-icon-plus" size="mini" plain
          @click="clickBoundDialog('updatePermission')">权限关联</el-button>
        <el-button type="success" icon="el-icon-plus" size="mini" plain
          @click="clickBoundDialog('updateMenu')">菜单关联</el-button>

      </el-col>
      <el-col :span="12" style="text-align:right">
        <el-tooltip class="item" effect="dark" :content="flg.searchFlg ? '隐藏搜索' : '展开搜索'" placement="top">
          <el-button icon="el-icon-search" size="mini" circle @click="flg.searchFlg = !flg.searchFlg"></el-button>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="刷新" placement="top">
          <el-button icon="el-icon-refresh" size="mini" circle @click="getRoleList"></el-button>
        </el-tooltip>
      </el-col>
    </el-row>
    <!-- 操作列表 -->

    <!-- 权限列表 -->
    <el-table :data="roleData" stripe style="width: 100%" v-loading="flg.loadingFlg">
      <el-table-column prop="id" label="序号" width="80">
        <template slot-scope="scope">
          <span>{{ (queryCondition.pageSize - 1) * queryCondition.pageNum + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="roleName" label="角色名称" width="300">
      </el-table-column>
      <el-table-column prop="isDelete" label="状态" width="120">
        <template slot-scope="scope">
          <el-tooltip :content="scope.row.isDelete == 0 ? '正常' : '停用'" placement="top">
            <el-switch :value="scope.row.isDelete == 0 ? true : false" active-color="#13ce66" inactive-color="#ff4949"
              @change="disableOrEnable(scope.row.isDelete, scope.row.id)">
            </el-switch>
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column prop="permission" label="关联权限" width="200">
        <template slot-scope="scope">
          <span v-for="(item, index) in scope.row.permission" :key="index">
            {{ item.permissionKey }} <br />
          </span>
        </template>
      </el-table-column>

      <el-table-column prop="menu" label="关联菜单" width="200">
        <template slot-scope="scope">
          <span v-for="(item, index) in scope.row.menu" :key="index">
            {{ item.menuName }} <br />
          </span>
        </template>
      </el-table-column>

      <el-table-column prop="remark" label="角色描述" width="600">
        <template slot-scope="scope">
          <el-input type="textarea" v-model="scope.row.remark" :readonly="true"></el-input>
        </template>
      </el-table-column>

      <el-table-column prop="creator" label="创建人" width="150">
			</el-table-column>
			<el-table-column prop="createDate" label="创建时间" width="160">
				<template slot-scope="scope">
					{{ formatDate(scope.row.createDate) }}
				</template>
			</el-table-column>
			<el-table-column prop="modifier" label="修改人" width="150">
			</el-table-column>
			<el-table-column prop="modifyDate" label="修改时间" width="160">
				<template slot-scope="scope">
					{{ formatDate(scope.row.modifyDate) }}
				</template>
			</el-table-column>

      <el-table-column label="操作" fixed="right" width="100">
        <template slot-scope="scope">
          <button type="button" v-show="scope.row.isDelete == 1" @click="clickDelete(scope.row.id)"
            class="el-button el-button--text el-button--mini">
            <i class="el-icon-edit">
              <span>彻底删除</span>
            </i>
          </button>

          <button type="button" v-show="scope.row.isDelete == 0" @click="clickDialog('update', scope.row.id)"
            class="el-button el-button--text el-button--mini">
            <i class="el-icon-edit">
              <span>修改</span>
            </i>
          </button>

          <button type="button" v-show="scope.row.isDelete == 0" @click="clickBoundDialog('updatePermission', scope.row)"
            class="el-button el-button--text el-button--mini">
            <i class="el-icon-edit">
              <span>权限关联</span>
            </i>
          </button>

          <button type="button" v-show="scope.row.isDelete == 0" @click="clickBoundDialog('updateMenu', scope.row)"
            class="el-button el-button--text el-button--mini">
            <i class="el-icon-edit">
              <span>菜单关联</span>
            </i>
          </button>

        </template>
      </el-table-column>
    </el-table>
    <!-- 权限列表 -->


    <!--    分页框-->
    <div class="block">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryCondition.pageSize" :page-sizes="[10, 20, 50, 100, 10000]" :page-size="queryCondition.pageNum"
        layout="total, sizes, prev, pager, next, jumper" :total="queryCondition.pageTotal">/
      </el-pagination>
    </div>
    <!--    分页框-->

    <!--    新增/修改 模态框-->
    <el-dialog :title="dialog.dialogTitle" :visible.sync="dialog.dialogFormVisible" width="40%" :append-to-body="true">
      <el-form :model="roleForm" :rules="rules" ref="roleForm" label-width="100px">

        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName" size="small"></el-input>
        </el-form-item>

        <el-form-item label="权限绑定" prop="permission" v-show="roleForm.id == ''">
          <el-select v-model="roleForm.permission" multiple clearable placeholder="请选择权限" style="width: 100%;"
            size="small">
            <el-option v-for="item in boundData.permission" :key="item.id" :label="item.permissionKey" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="菜单绑定" prop="menu" v-show="roleForm.id == ''">
          <el-cascader v-model="roleForm.menu" :options="boundData.menu" :props="boundData.menuProps" clearable
            style="width: 100%;" size="small"></el-cascader>
        </el-form-item>

        <el-form-item label="权限描述">
          <el-input type="textarea" v-model="roleForm.remark" size="small"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('roleForm')">确 定</el-button>
      </div>
    </el-dialog>
    <!--    新增/修改 模态框-->

    <!-- 关联权限 -->
    <el-dialog :title="dialog.dialogBoundTitle" :visible.sync="dialog.dialogVisibleBoundFlg" width="30%"
      :append-to-body="true">

      <el-form :model="roleForm" :rules="rules" ref="roleForm" label-width="100px">

        <table border="0" width="100%" cellpadding="10">
          <tbody>
            <tr>
              <td width="100px">
                <span style="color: red;">*</span> 角色名称
              </td>
              <td>
                <el-select v-model="roleForm.roleName" value-key="id" filterable clearable placeholder="请选择角色"
                  size="small" style="width: 100%;" @change="queryBoundPermissionOrMenu">
                  <el-option v-for="item in boundData.allRole" :key="item.id" :label="item.roleName" :value="item">
                  </el-option>
                </el-select>
              </td>
            </tr>

            <!-- 关联权限 -->
            <tr v-show="dialog.dialogBoundTitle == '权限关联'">
              <td width="100px">
                <span style="color: red;">*</span> {{ dialog.dialogBoundTitle }}

                <el-tooltip class="item" effect="dark" content="如果关联了权限则回写，反则为空" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
              </td>
              <td>
                <el-select v-model="roleForm.permission" multiple clearable placeholder="请选择权限" size="small"
                  style="width: 100%;">
                  <el-option v-for="item in boundData.permission" :key="item.id" :label="item.permissionKey"
                    :value="item.id">
                  </el-option>
                </el-select>
              </td>
            </tr>
            <!-- 关联权限 -->

            <!-- 关联菜单 -->
            <tr v-show="dialog.dialogBoundTitle == '菜单关联'">
              <td width="100px">
                <span style="color: red;">*</span> {{ dialog.dialogBoundTitle }}

                <el-tooltip class="item" effect="dark" content="关联菜单是根据父菜单查询的，如果未关联父菜单则查询失败" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
              </td>
              <td>
                <el-cascader v-model="roleForm.menu" :options="boundData.menu" :props="boundData.boundMenuProps" clearable
                  placeholder="请选择菜单" style="width: 100%;"></el-cascader>
              </td>
            </tr>
            <!-- 关联菜单 -->
          </tbody>
        </table>

      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog.dialogVisibleBoundFlg = false">取 消</el-button>
        <el-button type="primary" @click="submitFormBound">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 关联权限 -->
  </div>
</template>

<script>
import alter from '@/js/axios'
export default {
  name: "roleIndex",
  data() {
    return {
      roleData: [],
      queryCondition: {
        pageSize: 1,//查询第几页
        pageNum: 10,//一页显示多少行
        pageTotal: 0,//数据总数
        isDelete: "0",
        name: "",
      },
      flg: {
        loadingFlg: true,
        searchFlg: true,
      },
      //模态框的显示等
      dialog: {
        dialogFormVisible: false,
        dialogTitle: "",
        dialogVisibleBoundFlg: false, //打开绑定功能的flg
        dialogBoundTitle: "",//绑定权限、绑定菜单标题
      },
      //需要新增、修改的表单内容
      roleForm: {
        id: "",
        roleName: "",
        remark: "",
        permission: [],
        menu: []
      },
      //表单校验规则
      rules: {
        //菜单名称
        roleName: [
          { required: true, message: "请输入角色名称", trigger: 'blur' },
          { min: 2, max: 40, message: '长度在 2 到 40 个字符', trigger: 'blur' }
        ]
      },
      //绑定的数据：绑定权限、绑定菜单
      boundData: {
        permission: [],
        //来开启多选模式
        menuProps: {
          value: 'id',
          label: 'menuName',
          multiple: true,
          emitPath: true
        },
        menu: [],
        allRole: [],
        boundMenuProps: {
          value: 'id',
          label: 'menuName',
          multiple: true,
          emitPath: false
        }
      }

    }
  },
  created() {
    this.getRoleList()
    this.getBoundData()
  },
  methods: {
    handleSizeChange(val) {
      //  修改一页显示条数
      this.queryCondition.pageNum = val
      this.getRoleList()
    },
    handleCurrentChange(val) {
      //修改页数
      this.queryCondition.pageSize = val
      this.getRoleList()
    },
    //点击彻底删除权限按钮
    clickDelete(id) {
      this.$confirm("删除后将不可恢复，谨慎操作！！！", '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.completelyDeleteRole(id)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //点击显示新增/修改模态框
    clickDialog(type, id) {
      if (type == "insert") {
        this.dialog.dialogTitle = "新增角色"
        if (this.roleForm.id != "") {
          this.reset()
        }
      } else if (type == "update") {
        this.dialog.dialogTitle = "修改角色"
        this.roleForm.id = id
        this.selectRoleById()
      }
      this.dialog.dialogFormVisible = true
    },
    //点击关联权限、菜单
    clickBoundDialog(type, id) {
      //1.1查询所有关联角色
      this.getAllRole()

      if (type == "updatePermission") {
        this.dialog.dialogBoundTitle = "权限关联"
      } else if (type == "updateMenu") {
        this.dialog.dialogBoundTitle = "菜单关联"
      }

      if (id != undefined && id != "") {
        //2.1如果id不为空就通过id查询
        this.queryBoundPermissionOrMenu(id)
      } else {
        //2.2重置角色表单信息
        this.reset()
      }
      this.dialog.dialogVisibleBoundFlg = true
    },
    //获取所有角色
    getAllRole() {
      this.$axios.get("/role/selectAllRole").then(res => {
        let data = res.data.data
        this.boundData.allRole = data
      })
    },
    //查询角色绑定的权限 or 菜单
    queryBoundPermissionOrMenu(value) {
      //没值代表清空了角色名称
      if (value == "") {
        this.roleForm.id = ""
        this.roleForm.roleName = ""
        this.roleForm.permission = []
        this.roleForm.menu = []
        return false
      }
      this.roleForm.id = value.id
      this.roleForm.roleName = value.roleName
      if (this.dialog.dialogBoundTitle == '权限关联') {
        // //查询角色绑定的权限
        this.$axios.get("/role/queryPermissionBoundRoles?id=" + this.roleForm.id).then(res => {
          //遍历权限
          let data = res.data.data
          let permissionData = []
          if (data) {
            for (let i = 0; i < data.length; i++) {
              permissionData.push(data[i].id)
            }
          }
          this.roleForm.permission = permissionData
        })
      } else if (this.dialog.dialogBoundTitle == '菜单关联') {
        //查询角色绑定的菜单
        this.$axios.get("/role/queryRoleBoundMenus?id=" + this.roleForm.id).then(res => {
          //遍历菜单
          let data = res.data.data
          let menuData = []
          if (data) {
            for (let i = 0; i < data.length; i++) {
              menuData.push(data[i].id)
            }
          }
          this.roleForm.menu = menuData
        })

      }

    },
    //点击确认表单提交 权限关联、菜单关联
    submitFormBound() {
      if (this.roleForm.id == "") {
        alter.errorMessage("角色名称为空")
        return false
      }

      if (this.dialog.dialogBoundTitle == '权限关联') {
        //解析权限数据
        let newPermission = []
        this.roleForm.permission.forEach((val) => {
          newPermission.push({
            "id": val
          })
        })
        this.updateRole("permission", newPermission)
      } else if (this.dialog.dialogBoundTitle == '菜单关联') {
        //解析菜单数据
        let newMenu = []
        this.roleForm.menu.forEach(val => {
          newMenu.push({
            id: val
          })
        })
        this.updateRole("menu", newMenu)
      }
      this.dialog.dialogVisibleBoundFlg = false
    },
    //表单重置
    reset() {
      this.roleForm = {
        id: "",
        roleName: "",
        remark: "",
        permission: [],
        menu: []
      };
      if (this.$refs['form'] !== undefined) {
        this.$refs['roleForm'].resetFields();
      }
    },
    //查询需要绑定的相关数据【菜单、权限】
    getBoundData() {
      this.$axios.get("/permission/all").then(res => {
        this.boundData.permission = res.data.data
      })
      this.$axios.get("/menu/all").then(res => {
        this.boundData.menu = res.data.data

        //让element-ui的Cascader 级联选择器内容为空时候不显示
        this.getChild(this.boundData.menu);
      })
    },
    //让element-ui的Cascader 级联选择器内容为空时候不显示
    getChild(child) {
      for (let i = 0; i < child.length; i++) {
        if (child[i].children.length == 0) {
          child[i].children = undefined
        }
        if (child[i].children != null) {
          this.getChild(child[i].children)
        }
      }
    },
    //点击确认表单提交
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.dialog.dialogFormVisible = false
          //true:添加菜单 false修改菜单
          if (this.roleForm.id == "") {
            //解析权限
            let newPermission = []
            this.roleForm.permission.forEach((val) => {
              newPermission.push({
                "id": val
              })
            })
            //解析菜单
            let newMenu = []
            let newMenuData = this.parseMenu()
            newMenuData.forEach((val) => {
              newMenu.push({
                "id": val
              })
            })
            //调用新增角色
            this.insertRole(newPermission, newMenu)
          } else {
            this.updateRole()
          }
        } else {
          return false;
        }
      })
    },
    //获取不重复菜单编号
    parseMenu() {
      let val = this.roleForm.menu
      const setMenuId = new Set()

      for (let i = 0; i < val.length; i++) {
        for (let j = 0; j < val[i].length; j++) {
          setMenuId.add(val[i][j])
        }
      }
      return setMenuId
    },
    //停用/启用
    disableOrEnable(val, id) {
      let title = val == 0 ? "是否确认停用。停用后将不再显示！" : "是否确认启用。"
      this.$confirm(title + ', 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteRole(val, id);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    //通过id查询角色
    selectRoleById() {
      this.$axios.get("/role/selectRoleById?id=" + this.roleForm.id).then(res => {
        let data = res.data.data
        this.roleForm.id = data.id
        this.roleForm.roleName = data.roleName
        this.roleForm.remark = data.remark
      })
    },
    //新增角色
    insertRole(newPermission, newMenu) {
      let data = {
        roleName: this.roleForm.roleName,
        remark: this.roleForm.remark,
        permission: newPermission,
        menu: newMenu
      }
      this.$axios.post("/role/addRole", data).then(() => {
        this.getRoleList()
        this.reset()
      })
    },
    //停用角色
    deleteRole(val, id) {
      let isDelete = val == 0 ? 1 : 0
      let param = {
        id: id,
        isDelete: isDelete
      }
      this.$axios.delete("/role/deleteRole", { data: param }).then(() => {
        this.getRoleList()
      })
    },
    //彻底删除权限
    completelyDeleteRole(id) {
      let then = this
      this.$axios.delete("/role/completelyDeleteRole?id=" + id).then(function () {
        then.getRoleList()
      })
    },
    //修改权限
    updateRole(type, newData) {
      let data = {
        id: this.roleForm.id,
        roleName: this.roleForm.roleName,
        remark: this.roleForm.remark,
      }
      if (type == "permission") {
        data.permission = newData
      } else if (type == "menu") {
        data.menu = newData
      }

      this.$axios.put("/role/updateRole", data).then(() => {
        this.getRoleList()
        this.reset()
      })
    },
    //获取角色列表
    getRoleList() {
      let then = this
      then.flg.loadingFlg = true

      let data = {
        pageSize: this.queryCondition.pageSize,
        pageNum: this.queryCondition.pageNum,
        delete: this.queryCondition.isDelete,
        name: this.queryCondition.name
      }

      this.$axios.post("/role/limit", data).then(res => {
        let data = res.data.data
        then.roleData = data.list
        then.queryCondition.pageTotal = data.size
        then.flg.loadingFlg = false
      })
    }
  }
}
</script>

<style scoped></style>